package com.authine.cloudpivot.ext.service.impl;

import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.dto.system.OutApiClientDto;
import com.authine.cloudpivot.ext.model.yunshu.YsRequestModel;
import com.authine.cloudpivot.ext.model.yunshu.YsResultModel;
import com.authine.cloudpivot.ext.service.PunchoutService;
import com.authine.cloudpivot.ext.utils.system.OutApiClientApiUtils;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author hxd
 * @Date 2021/10/15 11:41
 * @Description 对外接口
 **/
@Slf4j
public class PunchoutServiceImpl implements PunchoutService {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final RestTemplate restTemplate = ApplicationContextUtils.getBean(RestTemplate.class);

    @Override
    @SneakyThrows
    public SingleResponse<YsResultModel> updateYunShuGoods(YsRequestModel ysRequestModel) {

        OutApiClientDto outApiClient = OutApiClientApiUtils.getByGomroUsername("punchout_yunshu");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        //a2kiikcrsvtkjaqc
        headers.add("EngineCode", outApiClient.getClient_id());
        //vSPrw92R+bPfCAvB0ggyMehB0UcGKlUFLsdTYy16kXBX3e4STqlx7g==
        headers.add("EngineSecret", outApiClient.getClient_secret());

        Map<String, String> body = new HashMap<>(4);
        body.put("ActionName", ysRequestModel.getActionName());
        body.put("Controller", ysRequestModel.getController());
        body.put("AppCode", ysRequestModel.getAppCode());
        body.put("PushDataList", ysRequestModel.getPushDataList());
        String bodyJson = objectMapper.writeValueAsString(body);

        log.warn("ys req-header:{}", headers);
        log.warn("ys req-body:{}", bodyJson);

        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(body, headers);

        //https://www.h3yun.com/OpenApi/Invoke
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(outApiClient.getResource_url(), httpEntity, String.class);

        log.warn("ys res:{}", stringResponseEntity.getBody());

        YsResultModel ysRequest = objectMapper.readValue(stringResponseEntity.getBody(), YsResultModel.class);
        return SingleResponse.of(ysRequest);
    }
}
